package com.br.aiops.listeners.ladder;

import com.br.aiops.counter.AlertLogCounter;
import com.br.aiops.counter.CounterLadderValue;

public class DurationAndAlertCountLadderJudge extends AbstractLadderJudge {

    public DurationAndAlertCountLadderJudge(AlertLogCounter alertLogCounter) {
        super(alertLogCounter);
    }

    @Override
    public void judgeLadder() {
        //特殊情况，如果日期在阶梯周期之前，则不统计
        LadderCycleStatus cycleStatus = super.initCycleIfAbsent();
        if (cycleStatus.beforeFirstCycle(counter.getAlertLog().getLogTime())) {
            return;
        }

        //统计该周期
        LadderCycleStatus counterStatus = super.countCycle(cycleStatus);
        int duration = counterStatus.getCurrentDuration(counter.getAlertLog().getLogTime());
        //如果是调度周期判断times，使用times step中的第一阶判断
        int times = counter.getRule().getDuration() == duration ?
                CounterLadderValue.getLadderValue(counter.counterKey()).getTimesStep().stream().findFirst().orElse(0)
                : CounterLadderValue.getTimesByDuration(counter.counterKey(), duration);

        //没有标识过则告警
        if (counterStatus.hasFlag(counter.getAlertLog().getLogTime())) {
            if (counterStatus.getCount(counter.getAlertLog().getLogTime()) >= times) {
                counterStatus.flag(counter.getAlertLog().getLogTime());
                sendAlert();
            }
        }
    }
}
